package com.crux.ribbon;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Optional;

@Slf4j
public class RequestUtil {
    public static enum WebType {
        Servlet, WebFlux, None;
    }

    public static WebType getWebType() {
        if (getHttpRequest().isPresent()) {
            return WebType.Servlet;
        } else {
            return WebType.None;
        }
    }

    public static HttpServletRequest getRequest() {
        HttpServletRequest request = null;
        try {
            request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        } catch (IllegalStateException e) {
            log.warn("不是http请求,没有request");
        }
        return request;
    }

    private static Optional<HttpServletRequest> getHttpRequest() {
        return Optional.ofNullable(getRequest());
    }

    public static Optional<Object> getAttr(String name) {
        return getHttpRequest().flatMap(request -> Optional.ofNullable(request.getAttribute(name)));
    }

    public static void setAttr(String name, Object value) {
        getHttpRequest().ifPresent(request -> request.setAttribute(name, value));
    }

    public static Optional<String> getParam(String key) {
        return getHttpRequest().flatMap(request -> Optional.ofNullable(request.getParameter(key)));
    }

    public static String getRequestUrl() {
        return getHttpRequest().isPresent() ? getHttpRequest().get().getRequestURL().toString() : null;
    }

    public static String getRequestUri() {
        return getHttpRequest().isPresent() ? getHttpRequest().get().getRequestURI() : null;
    }

    public static String getHeader(String name) {
        return getHttpRequest().isPresent() ? getHttpRequest().get().getHeader(name) : null;
    }

    public static List<String> getHeaderNames() {
        List<String> names = new ArrayList<>();
        if (getHttpRequest().isPresent()) {
            HttpServletRequest request = getHttpRequest().get();
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                names.add(headerNames.nextElement());
            }
        }
        return names;
    }


}
